package com.mnsq.user.service.impl;

import com.mnsq.common.bean.dto.LoginInfo;
import com.mnsq.common.bean.entity.user.Account;
import com.mnsq.common.bean.entity.user.User;
import com.mnsq.common.bean.enums.TimeEnum;
import com.mnsq.common.dao.AccountRepository;
import com.mnsq.common.dao.UserRepository;
import com.mnsq.common.service.RedisServer;
import com.mnsq.common.tools.jpa.JpaExample;
import com.mnsq.common.tools.jpa.ReflectValueUtil;
import com.mnsq.common.tools.tool.UUIDUtils;
import com.mnsq.user.bean.condition.AccountCondition;
import com.mnsq.user.service.AccountService;
import matrix.module.common.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.Optional;

/**
 * @author Administrator
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRepository ar;

    @Autowired
    private UserRepository ur;

    @Autowired
    private RedisServer redisServer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result register(AccountCondition ac) {
        String result;
        if ((result = ac.valid()) != null) {
            return Result.fail(result);
        }
        if (!notExistAccount(ac.getAccount())) {
            return Result.fail("用户名已存在");
        }
        Account acc = new Account();
        acc.createInit();
        ReflectValueUtil.getInstance().convertToObject(ac, acc);
        User usr = new User().setPetName(UUIDUtils.getUserName());
        usr.createInit();
        usr.setRoleId(4L);
        usr.setUnique(UUIDUtils.getUnique());
        usr.setCreateTime(new Date());
        ur.saveAndFlush(usr);
        acc.setUserId(usr.getId());
        acc.setCreateTime(new Date());
        ar.saveAndFlush(acc);
        return Result.success(null);
    }

    @Override
    public Result existAccount(AccountCondition ac) {
        if (notExistAccount(ac.getAccount())) {
            return Result.success("");
        }
        return Result.fail("用户名已存在");
    }

    /**
     * 用户名是否不存在
     *
     * @param account
     * @return true：不存在；false：存在；
     */
    private boolean notExistAccount(String account) {
        if (account == null) {
            return true;
        }
        return CollectionUtils.isEmpty(ar.findAll(JpaExample.getInstance().getExample(new AccountCondition().setAccount(account), new Account())));
    }

    @Override
    public Result bind(AccountCondition ac) {
        return null;
    }

    @Override
    public Result login(AccountCondition ac) {
        String result;
        if ((result = ac.valid()) != null) {
            return Result.fail(result);
        }
        Optional<Account> one = ar.findOne(JpaExample.getInstance().getExample(ac, ac.getInstance()));
        if (one.isPresent()) {
            // 绑定用户信息，返回token
            String token = UUIDUtils.getToken();
            Account account = one.get();
            LoginInfo loginInfo = getInfo(account.getUserId()).setInfo(account).setToken(token);
            redisServer.del(account.getToken());
            account.setToken(token);
            redisServer.setValue(token, loginInfo, TimeEnum.DAY_FIFTEEN.time);
            ar.saveAndFlush(account);
            return Result.success(loginInfo);
        }
        return Result.fail("登录失败，用户名或密码错误");
    }

    @Override
    public Result logout(String token) {
        redisServer.del(token);
        return Result.success(null);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    private LoginInfo getInfo(Long userId) {
        Optional<User> user = ur.findById(userId);
        return LoginInfo.getInstance().setInfo(user.orElse(new User()));
    }
}
